package com.baosight.risk.web.xtaa.code;

import com.baosight.risk.api.xtaa.code.IXtaaCodeService;
import com.baosight.risk.api.xtaa.code.IXtaaCodeTypeService;
import com.baosight.risk.base.controller.BaseController;
import com.baosight.risk.base.entity.MultipleUpdateStatus;
import com.baosight.risk.common.annotation.Log;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.enums.BusinessType;
import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.common.utils.JSONUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.service.xtaa.code.entity.XtaaCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.Map;

/**
 * @desc:
 * @author: CuiShiHao
 **/
@Slf4j
@RestController
@RequestMapping("xtaa/code/data")
@Api(value = "系统数据字典", description = "系统数据字典", produces = MediaType.APPLICATION_JSON)
public class XtaaCodeController extends BaseController {


    @Autowired
    private IXtaaCodeService xtaaCodeService;

    @Autowired
    private IXtaaCodeTypeService xtaaCodeTypeService;


    @ApiOperation("根据字典类别编码获取字典列表仅启用")
    @RequestMapping(value = "/list", method = RequestMethod.GET, name = "获取字典列表", produces = "application/json")
    public AjaxResult subsetList(@RequestParam(value = "ddTypeCode", required = false) String ddTypeCode) {
        startPage();
        List<XtaaCode> list = xtaaCodeService.selectDataByDDTypeCode(ddTypeCode);
        return getResultPage(list);
    }

    @ApiOperation("根据字典类别编码获取字典列表全部数据：启用禁用")
    @RequestMapping(value = "/allList", method = RequestMethod.GET, name = "获取字典列表", produces = "application/json")
    public AjaxResult subsetAllList(@RequestParam(value = "ddTypeCode", required = false) String ddTypeCode) {
        startPage();
        List<XtaaCode> list = xtaaCodeService.selectAllDataByDDTypeCode(ddTypeCode);
        return getResultPage(list);
    }

    @ApiOperation("根据字典类别编码,和名称DDName模糊查询字典列表")
    @RequestMapping(value = "/fuzylist", method = RequestMethod.POST, name = "获取字典列表", produces = "application/json")
    public AjaxResult subsetFuzyList(@RequestBody Map map) {
        String ddName = map.get("ddName").toString();
        String ddTypeCode = map.get("ddTypeCode").toString();
        startPage();
        System.out.println(ddName);
        List<XtaaCode> list = xtaaCodeService.selectDataByDDTypeCodeAndDDName(ddTypeCode, ddName);
        return getResultPage(list);
    }

    @ApiOperation("根据字典类型编码，parentID。用于懒加载下一级数据")
    @RequestMapping(value = "/lazyList", method = RequestMethod.GET, name = "获取字典列表", produces = "application/json")
    public AjaxResult subsetLazyList(@RequestParam(value = "ddTypeCode") String ddTypeCode, @RequestParam(value = "ddCode") String parentID) {
        startPage();
        List<XtaaCode> list = xtaaCodeService.selectLazyDataByCodeAndParent(ddTypeCode, parentID);
        return getResultPage(list);
    }

    @ApiOperation("根据字典类型编码，parentID。用于懒加载下一级数据")
    @RequestMapping(value = "/lazyRiskList", method = RequestMethod.GET, name = "获取字典列表", produces = "application/json")
    public AjaxResult lazyRiskList(@RequestParam(value = "ddTypeCode") String ddTypeCode, @RequestParam(value = "parentID") String parentID) {
        startPage();
        List<XtaaCode> list = xtaaCodeService.selectLazyRiskDataByCodeAndParent(ddTypeCode, parentID);
        return getResultPage(list);
    }

    @ApiOperation("根据字典类型编码，parentID。用于懒加载下一级数据（用于个人指标分析）")
    @RequestMapping(value = "/personalLazyList", method = RequestMethod.GET, name = "获取字典列表", produces = "application/json")
    public AjaxResult personalLazyList(@RequestParam(value = "ddTypeCode") String ddTypeCode, @RequestParam(value = "parentID") String parentID) {
        startPage();
        List<XtaaCode> list = xtaaCodeService.selectLazyRiskDataByCodeAndParent(ddTypeCode, parentID);
        for (XtaaCode xtaaCode : list) {
            // 只过滤内部指标，不过滤外部指标
            // 只过滤最后一层的节点
            if ("1".equals(xtaaCode.getIsEndLevel()) && xtaaCode.getDdCode().startsWith("ZBN")){
                return getResultPage(xtaaCodeService.codeFilter(list));
            }
        }
        return getResultPage(list);
    }

    @GetMapping("getlist")
    public AjaxResult subsetListByGet(String ddTypeCode) {
        startPage();
        List<XtaaCode> list = xtaaCodeService.selectDataByDDTypeCode(ddTypeCode);
        return getResultPage(list);
    }

    @GetMapping("add/{id}")
    public AjaxResult add(@PathVariable("id") String id) {
        return success(xtaaCodeTypeService.get(id));
    }

    @ApiOperation("新增数据字典")
    @PostMapping("save")
    @Log(title = "字典数据新增", businessType = BusinessType.INSERT)
    @RequiresPermissions("xtaa:code:data:save")
    public AjaxResult save(@RequestBody XtaaCode xtaaCode) {
        //初始化基本参数
        xtaaCode = (XtaaCode) BeanUtils.initBean(xtaaCode);
        if (StringUtils.isBlank(xtaaCode.getStatus())) {
            xtaaCode.setStatus("10");
        }
        log.info("字典数据添加：" + xtaaCode.toString());
        return toAjax(xtaaCodeService.insertCode(xtaaCode));
    }

    @ApiOperation("获取数据字典实体")
    @RequestMapping(value = "/getItem", method = RequestMethod.GET, name = "获取字典")
    public AjaxResult edit(String id) {
        XtaaCode xtaaCode = xtaaCodeService.get(id);
        if (xtaaCode == null) {
            return error("数据不存在");
        }
        return success(xtaaCode);
    }

    @ApiOperation("更新数据字典")
    @PostMapping("update")
    @Log(title = "字典数据编辑")
    public AjaxResult update(@RequestBody XtaaCode xtaaCode) {
        log.info("字典数据编辑：" + xtaaCode.toString());
        return toAjax(xtaaCodeService.updateCode(xtaaCode));
    }

    @ApiOperation("批量更新字典状态")
    @Log(title = "批量更新状态")
    @RequestMapping(value = "updateStatus", method = RequestMethod.PUT)
    public AjaxResult updateStatus(@RequestBody MultipleUpdateStatus updateStatus) {
        updateStatus = (MultipleUpdateStatus) BeanUtils.updateBean(updateStatus);
        return toAjax(xtaaCodeService.multipleUpdateStatus(updateStatus));
    }

    @PostMapping("delete")
    @Log(title = "字典数据删除", businessType = BusinessType.DELETE)
    public AjaxResult delete(@RequestBody Map<String, Object> map) {
        return toAjax(xtaaCodeService.deleteByIds(map));
    }

    /**
     * 根据字典类型返回字典数据详细信息
     *
     * @return
     */
    @GetMapping("detail")
    public AjaxResult detail(String ddTypeCode) {
        List<XtaaCode> list = xtaaCodeService.selectDataByDDTypeCode(ddTypeCode);

        JSONArray jsonArray = JSONArray.fromObject(list);

        return success(jsonArray);
    }

    /**
     * 根据父节点id获取下级数据（仅子集）
     *
     * @param id 父节点id
     * @return
     */
    @GetMapping("subset/{id}")
    public AjaxResult getSubsetByParentID(@PathVariable("id") String id) {

        List<XtaaCode> list = xtaaCodeService.selectSubsetByParentID(id);
        JSONArray jsonArray = JSONArray.fromObject(list);
        return success(jsonArray);
    }

    /**
     * 根据父节点id获取下级数据（包含子集孙集）
     *
     * @param id 父节点id
     *           `
     */
    @GetMapping("allsubset/{id}")
    public AjaxResult getAllSubsetByParentID(@PathVariable("id") String id) throws Exception {
        List<XtaaCode> list = xtaaCodeService.selectAllSubsetByParentID(id);
        JSONArray jsonArray = JSONArray.fromObject(list);
        JSONUtils.filterJSONArrayNull(jsonArray);
        return success(jsonArray);
    }

    /**
     * 根据编码获取下级数据（包含子集孙集）
     *
     * @param ddCode 字典编码
     * @return
     */
    @GetMapping("listByDdcode")
    public AjaxResult selectAllSubsetByDdCode(String ddCode) {
        List<XtaaCode> list = xtaaCodeService.selectAllSubsetByDDCode(ddCode);
        return success(list);
    }
    @GetMapping("listByParentCode")
    public AjaxResult listByParentCode(@RequestParam("ddType") String ddType,@RequestParam("parentCode") String parentCode) {
        List<XtaaCode> list = xtaaCodeService.listByParentCode(ddType,parentCode);
        return success(list);
    }


}
